package org.yylnb.openplatform.monitor.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.yylnb.openplatform.monitor.event.EventBean;
import org.yylnb.openplatform.monitor.event.EventType;
import org.yylnb.openplatform.monitor.service.api.SearchService;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.Map;


/**
 * @author RainLin
 * @date 2020/8/3 - 19:17
 */
@Component
public class AvgJob implements SimpleJob {
    @Autowired
    private ApplicationContext context;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 设置服务的最高耗时阈值10毫秒
     */
    private int maxTime = 10;
    @Autowired
    private SearchService searchService;
    @Override
    public void execute(ShardingContext shardingContext) {
        //请求搜索模块,查询结果,遍历结果
        Instant now = Instant.now();
        Date to = Date.from(now.plusSeconds(-3600*8));
        //计算60秒之前的时间
        Date from = Date.from(now.plusSeconds(-60-3600*8));
        Map<String, Integer> avg = searchService.statAvg(simpleDateFormat.format(from), simpleDateFormat.format(to));
        System.err.println(avg);
        for (Map.Entry<String, Integer> entry : avg.entrySet()) {
            //每一个接口的名字
            String key = entry.getKey();
            //平均时间
            Integer value = entry.getValue();
            //如果时间超出阈值,需要告警
            if (value>maxTime) {
                //我们告警的方式确定吗? 可能会同时采用邮件,APP,网络电话等方式
                EventBean bean = new EventBean();
                bean.setEventType(EventType.OVERTIME);
                bean.setMsg("服务:"+key+"  响应时间超出了阈值,本次平均时间为:"+value);
                //发送事件
                context.publishEvent(bean);
            }
        }

    }
}

